<?php

class ControllerToolCopyrestock extends Controller {

    public function get_customer_id(){

        $cus_name = trim(I('get.cus_name'));
        $this->load->model('tool/copyrestock');
        if (empty($cus_name)) {
            $json['error']='输入有误';
        }else{
            $data['customer_id'] = $this->model_tool_copyrestock->getCustomer($cus_name);

            if (empty($data['customer_id'])) {
                $json['error']='输入有误';
            }else{
                $json = $data;
            }
        }


        echo json_encode($json);
    }

    public function get_solution_id(){

        $shelf_id = trim(I('get.shelf_id'));
        $this->load->model('tool/copyrestock');
        if (empty($shelf_id)) {
            $json['error']='输入有误';
        }else{
            $data['solution_id'] = $this->model_tool_copyrestock->get_solution_id($shelf_id);
            $data['shelf_id'] = $shelf_id;

            if (empty($data['solution_id'])) {
                $json['error']='输入有误';
            }else{
                $json = $data;
            }
        }


        echo json_encode($json);
    }
    //--------------------------------------------
    public function get_shelfname(){

       $solution_id = trim(I('get.solution_id'));
        $this->load->model('tool/copyrestock');
        $results = $this->model_tool_copyrestock->get_shelfname($solution_id);

        $this->response->setOutput(json_encode($results));
    }

    public function getshelfname(){

       $shop_id = trim(I('get.shop_id'));
       $customer_id = trim(I('get.customer_id'));
        $this->load->model('tool/copyrestock');

        if($shop_id!=="undefined"){
             $results = $this->model_tool_copyrestock->getshelfname($shop_id);
        }else{
              $results = $this->model_tool_copyrestock->get_shelfinfo($customer_id);
        }


        $this->response->setOutput(json_encode($results));

    }

    public function changeop(){

       $shelf_product_id = trim(I('get.shelf_product_id'));
       $shelf_id = trim(I('get.shelf_id'));
       $shelf_x = trim(I('get.shelf_x'));
       $shelf_y = trim(I('get.shelf_y'));

        $this->load->model('tool/copyrestock');
        $results['success'] = $this->model_tool_copyrestock->changeop($shelf_product_id,$shelf_id,$shelf_x,$shelf_y);

        $this->response->setOutput(json_encode($results));

    }



    public function copystock(){

       $shelf_product_id = trim(I('get.shelf_product_id'));
       $stock_num = trim(I('get.stock_num'));
        $this->load->model('tool/copyrestock');
        $results = $this->model_tool_copyrestock->copystock($shelf_product_id,$stock_num);

        $this->response->setOutput(json_encode($results));

    }
//--------------
    public function get_shelf(){

       $solution_id = trim(I('get.solution_id'));
        $this->load->model('tool/copyrestock');
        $results = $this->model_tool_copyrestock->getshelf($solution_id);

        if($results){
            $this->formatShelf($results);
        }

    }

    public function get_shelfinfo(){
        $shop_id = trim(I('get.shop_id'));
        $shelfIds = trim(I('get.shelf_id'));
        $customer_id = trim(I('get.customer_id'));

        $this->load->model('tool/copyrestock');
        if($shop_id!=="undefined"){
              $results = $this->model_tool_copyrestock->getshelfinfo($shop_id);
        }else{
              $results = $this->model_tool_copyrestock->getcustshelf($shelfIds);
        }

        if($results){

            $this->formShelf($results);
        }

    }


    //优化
    public function W_get_shelfinfo(){
        $shop_id = trim(I('get.shop_id'));
        $shelfIds = trim(I('get.shelf_id'));
        $customer_id = trim(I('get.customer_id'));

        $this->load->model('tool/copyrestock');
        if($shop_id!=="undefined"){
              $results = $this->model_tool_copyrestock->getshelfinfo($shop_id);
        }else{
              $results = $this->model_tool_copyrestock->getcustshelf($shelfIds);
        }

        if($results){

            $this->W_formShelf($results,$shelfIds);
        }

    }

    //优化货架详细信息------------------------------------------------------
    public function formatShelf($data){

        $this->load->model('tool/image');
        $this->load->model('tool/copyrestock');

        $json = array('success' => true);

        foreach($data as $v){

            /*货架缩略图*/
            if ($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
                $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*货架缩略图*/

            /*货架商品详细*/
            $shelfProduct = array();
            $shelfProducts = $this->model_tool_copyrestock->getShelfProducts($v['shelf_id']);
            foreach($shelfProducts as $key => $v2){
                $shelfProduct[$key] = $this->getProductInfo($v2);
                if($shelfProduct[$key] != null){
                    $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
                    $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
                    $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
                    $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
                    $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
                    $shelfProduct[$key]['stock_qty_temp'] = $v2['stock_qty_temp'];
                }
            }
            /*货架商品详细*/

            // $shelf_name = $v['cname'].$payGrade[$v['pay_grades']]."级别".$shelfType[$v['shelf_type']]."货架";
            $shelf_id = $v['shelf_id'];
            $json['shelf'][$shelf_id] = array(
                'shelf_id' => $v['shelf_id'],
                'image' => $image,
                'shelf_name' => $v['shelf_name'],
                'category_id' => $v['category_id'],
                'scount' => 1,
                'shelfProduct' => array_values(array_filter($shelfProduct)) //去空数组重编index
            );
        }

//echo '<br /><br /><br />';


        $this->response->setOutput(json_encode($json));

    }

      public function formShelf($data){

        $this->load->model('tool/image');
        $this->load->model('tool/copyrestock');

        $json = array('success' => true);
        foreach($data as $v){

            /*货架缩略图*/
            if ($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
                $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*货架缩略图*/

            /*货架商品详细*/
            $shelfProduct = array();
            $shelfProducts = $this->model_tool_copyrestock->getShelfProducts($v['shelf_id']);
            foreach($shelfProducts as $key => $v2){
                $shelfProduct[$key] = $this->getProductInfo($v2);
                if($shelfProduct[$key] != null){
                    $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
                    $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
                    $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
                    $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
                    $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
                    $shelfProduct[$key]['stock_qty_temp'] = $v2['stock_qty_temp'];

                }
            }
            /*货架商品详细*/

            // $shelf_name = $v['cname'].$payGrade[$v['pay_grades']]."级别".$shelfType[$v['shelf_type']]."货架";
            $shelf_id = $v['shelf_id'];
            $json['shelf'][$shelf_id] = array(
                'shelf_id' => $v['shelf_id'],
                'image' => $image,
                'shelf_name' => $v['shelf_name'],
                'category_id' => $v['category_id'],
                'scount' => 1,
                'shelfProduct' => array_values(array_filter($shelfProduct)) //去空数组重编index
            );
        }



        $this->response->setOutput(json_encode($json));

    }

    //优化
     public function W_formShelf($data,$shelfIds){

        $this->load->model('tool/image');
        $this->load->model('tool/copyrestock');

        $json = array('success' => true);
        foreach($data as $v){

            /*货架缩略图*/
            if ($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
                $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*货架缩略图*/

            /*货架商品详细*/
            $shelfProduct = array();
            $shelfProducts = $this->model_tool_copyrestock->getShelfProducts($shelfIds);
            //var_dump($shelfProducts);die;
            foreach($shelfProducts as $key => $v2){
                $shelfProduct[$key] = $this->getProductInfo($v2);
                if($shelfProduct[$key] != null){
                    $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
                    $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
                    $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
                    $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
                    $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
                    $shelfProduct[$key]['stock_qty_temp'] = $v2['stock_qty_temp'];
                    $shelfProduct[$key]['stock_qty'] = $v2['stock_qty'];
                }
            }
             //var_dump($shelfProducts);die;
            /*货架商品详细*/

            // $shelf_name = $v['cname'].$payGrade[$v['pay_grades']]."级别".$shelfType[$v['shelf_type']]."货架";
            $shelf_id = $v['shelf_id'];
            $json['shelf'][$shelf_id]['shelf_id'] = $v['shelf_id'];
            $json['shelf'][$shelf_id]['image'] =  $image;
            $json['shelf'][$shelf_id]['shelf_name'] = $v['shelf_name'];
            $json['shelf'][$shelf_id]['category_id'] = $v['category_id'];
            $json['shelf'][$shelf_id]['scount'] = 1;
            if($shelf_id==$shelfIds){
                $json['shelf'][$shelf_id]['shelfProduct'] = array_values(array_filter($shelfProduct));
            }

        }




        $this->response->setOutput(json_encode($json));

    }


    public function get_shelf_products(){

        $shelf_id = trim(I('get.shelfid'));
        // echo 111;
        $this->load->model('tool/copyrestock');

        $shelfProducts = $this->model_tool_copyrestock->getShelfProducts($shelf_id);
        foreach($shelfProducts as $key => $v2){
            $shelfProduct[$key] = $this->getProductInfo($v2);
            if($shelfProduct[$key] != null){
                $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
                $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
                $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
                $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
            }
        }
        $json = $shelfProduct;


        // var_dump($json);
        echo json_encode($json);
    }
    //搜索
    public function searchproduct(){

        $solution_id = trim(I('get.solution_id'));
        $searchInput = trim(I('get.searchInput'));
        $this->load->model('tool/copyrestock');
        $results = $this->model_tool_copyrestock->SerShelfProducts($solution_id,$searchInput);
        // $shelfProducts = $this->model_tool_copyrestock->getShelfProducts($v['shelf_id']);
        // foreach($shelfProducts as $key => $v2){
        //     $shelfProduct[$key] = $this->getProductInfo($v2);
        //     if($shelfProduct[$key] != null){
        //         $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
        //         $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
        //         $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
        //         $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
        //         $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];

        //     }
        // }
        // $this->response->setOutput(json_encode($results));

    }

        //获取单个商品必要信息
    public function getProductInfo($data){

        $this->load->model('catalog/product');

        $retval = array();
        $id = $data['product_id'];
        $result = $this->model_catalog_product->getListProduct($id);

        if($result){

            $product = $result[0];

            $this->load->model('tool/image');
            $this->load->model('catalog/category');


            /*product image*/
            if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
                $image = $this->model_tool_image->resize($product['image'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*product image*/



            /*options选项*/
            foreach ($this->model_catalog_product->getProductOptions($product['product_id']) as $option) {
                if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
                    $option_value_data = array();
                    if(!empty($option['product_option_value'])){
                        foreach ($option['product_option_value'] as $option_value) {
                            //!$option_value['subtract'] || ($option_value['quantity'] > 0)
                            if (true) {
                                if ((($this->customer->isLogged() && $this->config->get('config_customer_price')) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                                    $price = $this->currency->restFormat($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                } else {
                                    $price = $this->currency->restFormat($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                }

                                if (isset($option_value['image']) && file_exists(DIR_IMAGE . $option_value['image'])) {
                                    $option_image = $this->model_tool_image->resize($option_value['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                } else {
                                    $option_image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                }

                                $option_value_data[] = array(
                                    'image'                 => $option_image,
                                    'price'                 => $price,
                                    'price_formated'        => $price_formated,
                                    'price_prefix'          => $option_value['price_prefix'],
                                    'product_option_value_id'=> $option_value['product_option_value_id'],
                                    'option_value_id'       => $option_value['option_value_id'],
                                    'name'                  => $option_value['name'],
                                    'quantity'  => !empty($option_value['quantity']) ? $option_value['quantity'] : 0
                                );
                            }
                        }
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value_data,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true

                    );

                } elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
                    $option_value  = array();
                    if(!empty($option['product_option_value'])){
                        $option_value = $option['product_option_value'];
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true
                    );
                }
            }
            /*options选项*/

            /*原价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

            /*原价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

            /*special特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            /*special特价*/

            $show_cart = 1;
            if($product['is_single'] != 1){
                $show_cart = 0;
            }
            else if( $options[0]['option_value'][0]['quantity'] < $product['minimum']){
                $show_cart = 2;
            }

            $days = (int)((time()-strtotime($product['date_added']))/(24*3600));
            if(($days < 60 || $product['newpro'] == 1) && $product['show_new'] == 1){
                $show_new = 1;
            }
            else{
                $show_new = 0;
            }
            if ($product['clearance']||$product['lack_status']==3) {
                $clearqty = $this->model_catalog_product->getclearqty($product['product_id']);
            }
            $parameter=substr($product['sku'], -6);
            $retval = array(
                'id' => $product['product_id'],
                'product_code' => $product['product_code'],
                'sku' => $product['sku'],
                'parameter' => $parameter,
                'name' => $product['name'],
                'image' => $image,
                'price' => $price,
                'price_formated'    => $price_formated,
                'special' => $special,
                'special_formated'  => $special_formated,
                'minimum' => $product['minimum'] ? $product['minimum'] : 1,
                'buyqty' => 0,
                'options'    => $options,
                'quantity' => $product['quantity'],
                'show_new' => $show_new,
                'recommend' => $product['recommend'],
                'clearance' => $product['clearance'],
                'lack_status' => $product['lack_status'],
                'lack_reason' => $product['lack_reason'],
                'promotion' => $product['promotion'],
                'is_single' => $product['is_single'],
                'option_value_quantity' => $options[0]['option_value'][0]['quantity'],
                'show_cart' => $show_cart,
                'clearqty' => $clearqty ,


                'sort_order' => $product['sort_order']
            );

            return $retval;

        }

    }

    //添加商品
    public function addproduct(){
        // echo 11;
        $now = date('Y-m-d H:i:s');
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $this->load->model('tool/copyrestock');
        $shelf_index = $data['shelf_index'];
        $addlist = $data['addlist'];
        foreach ($addlist as $key => $value) {
            $pcode = $value['product_code'];
            $list[$pcode] = $value;

        }
        $results = $this->model_tool_copyrestock->addproduct($list,$shelf_index);

        $this->response->setOutput(json_encode($results));
    }


        //首次补货---------
    public function addToOrder(){
        $now = date('Y-m-d H:i:s');
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $buyproducts = $data['buyproducts'];
        foreach ($buyproducts as $key => $value) {
            $productskey = $value['id']."_".$value['product_code'].'0';
            $shelfIds[] = $value['shelf_id'];
            $products[$productskey]['price'] = $value['special'];
            $products[$productskey]['buy_qty'] = $value['buyqty'];

            $products[$productskey]['shelf_info']['S']= $value['shelf_id'];
            $products[$productskey]['shelf_info']['Y']= $value['shelf_y'];
            $products[$productskey]['shelf_info']['X']= $value['shelf_x'];
            // .';Y:'.$value['shelf_y'].';X:'.$value['shelf_x'];
            $products[$productskey]['shelf_info']['qty'] = $value['buyqty'];
        }
        $shelfIds = array_unique($shelfIds);
        // var_dump($shelfIds);
        // var_dump($products);
        //die();
        // extract($this->_solutionSave($data, $now));

        $shelfOrderId = $this->_shelfOrderSave($data, $shelfIds, $products, $now);
        //客户提交补货单后，需要业务员线下确认，通过后提交成系统后台订单，进入发货流程。
        $this->_addNewSystemTaskByShelfOrderId($shelfOrderId, $now);
        //$orderId = $this->_cpShelfOrderToOrder($shelfOrderId);

        $json['success'] = true;
        $this->response->setOutput(json_encode($json));
    }

    //保存购买的方案、货架、货架商品信息，汇总货架商品信息后返回
    protected function _solutionSave($data, $now) {
        $shelfIds = array();
        $products = array();
        $this->load->model('ssl/solution');
        $newSolutionInfo = array(
            'customer_id' => $data['customerId'],
            'solution_name' => $data['customerId'].'_'.time(),
            'date_added' => $now,
        );
        $newSolutionId = $this->model_ssl_solution->addNew($newSolutionInfo);
        $modifySolutionInfo = array();
        $this->load->model('ssl/shelf');
        foreach ($data['buylist'] as $k=>$shelfInfo) {
            $newShelfInfo = array(
                'solution_id' => $newSolutionId,
                'customer_id' => $data['customerId'],
                'shelf_name' => $shelfInfo['name'],
                //'shelf_type' => '',
                //'shop_type' => '',
                //'pay_grades' => '',
                'parent_shelf' => $shelfInfo['shelf_id'],
                'date_added' => $now,
            );
            $newShelfId = $this->model_ssl_shelf->addNew($newShelfInfo);
            $shelfIds[] = $newShelfId;
            $modifySolutionInfo['shelf_length'] += 1;
            $modifyShelfInfo = array();
            foreach ($shelfInfo['shelfProduct'] as $kk=>$productInfo) {
                $newShelfProductInfo = array(
                    'shelf_id' => $newShelfId,
                    'product_id' => $productInfo['id'],
                    'product_code' => $productInfo['pov_code'],
                    'shelf_layer' => $productInfo['shelf_y'],
                    'layer_position' => $productInfo['shelf_x'],
                    'show_qty' => $productInfo['minimum'],
                    'min_order_qty' => $productInfo['minimum'],
                    'date_added' => $now,
                );
                if ($this->model_ssl_shelf->addNewProduct($newShelfProductInfo)){
                    $modifyShelfInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifyShelfInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifyShelfInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $modifySolutionInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifySolutionInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifySolutionInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['price'] = $productInfo['special'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['buy_qty'] += $productInfo['shelf_quantity'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['shelf_info'] =array(
                            'S'=>$newShelfId,
                            'Y'=>$productInfo['shelf_y'],
                            'X'=>$productInfo['shelf_x'],
                            'qty' => $productInfo['shelf_quantity'],
                    );
                }
            }
            foreach ($modifyShelfInfo as $kk=>$value) {
                $modifyShelf[$kk] = ','.implode(',', array_keys($value)).',';
            }
            $this->model_ssl_shelf->modifyByPK($newShelfId, $modifyShelf);
        }
        foreach ($modifySolutionInfo as $k=>$value) {
            $modifySolution[$k] = ','.implode(',', array_keys($value)).',';
        }
        $this->model_ssl_solution->modifyByPK($newSolutionId, $modifySolution);
        return compact('shelfIds', 'products');
    }
     //改善补货
     public function W_addToOrder(){
        $now = date('Y-m-d H:i:s');
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $buyproducts = $data['buyproducts'];

        foreach ($buyproducts as $key => $value) {
            $productskey = $value['product']['id']."_".$value['product']['product_code'].'0';
            $shelfIds[] = $value['shelf_id'];
            $products[$key][$productskey]['price'] = $value['product']['special'];
            $products[$key][$productskey]['buy_qty'] = $value['stock_qty'];
            $products[$key][$productskey]['shelf_product_id']= $value['shelf_product_id'];
            $products[$key][$productskey]['shelf_info']['S']= $value['shelf_id'];
            $products[$key][$productskey]['shelf_info']['Y']= $value['shelf_layer'];
            $products[$key][$productskey]['shelf_info']['X']= $value['layer_position'];
            $products[$key][$productskey]['shelf_info']['qty'] = $value['stock_qty'];
          $this->db->query("UPDATE shelf_product SET stock_qty=0 WHERE shelf_product_id=".$value['shelf_product_id']);
        }

        $shelfIds = array_unique($shelfIds);

        //客户提交补货单后，需要业务员线下确认，通过后提交成系统后台订单，进入发货流程。
        $this->_addNewSystemTaskByShelfOrderId($data, $shelfIds, $products,  $now);


        $json['success'] = true;
        $this->response->setOutput(json_encode($json));
    }
    //优化shelf_order和shelf_product
     protected function W_shelfOrderSave($data, $shelfIds, $products, $now) {
        $this->load->model('ssl/order');
        $this->load->model('ssl/shelf_order');
        //shelf_order添加
        $shelfOrderInfo = array(
            'customer_id' => $data['customerId'],
            'shelf_ids' => implode(',', $shelfIds),
            'add_name' => $data['sendaddress']['name'],
            'add_tel' => $data['sendaddress']['tel'],
            'add_country' => $data['sendaddress']['country'],
            'add_city' => $data['sendaddress']['city'],
            'add_zone' => $data['sendaddress']['zone'],
            'add_address' => $data['sendaddress']['address'],
            'add_company' => $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'paycode' => $data['paycode'],
            'order_price' => $data['allprice'],
            'date_added' => $now,
            'date_customer_check' => $now,
            'date_user_check' => $now,//调试创建订单方法
        );
        $shelfOrderId = $this->model_ssl_shelf_order->addNew($shelfOrderInfo);
        foreach ($products as $key => $value) {
            foreach ($value as $unique=>$info) {
                list($productId, $productCode) = explode('_', $unique);
                    $shelfOrderProductInfo = array(
                        'shelf_order_id' => $shelfOrderId,
                        'customer_id' => $data['customerId'],
                        'product_id' => $productId,
                        'product_code' => $productCode,
                        'shelf_info' => json_encode($info['shelf_info']),
                        'price' => $info['price'],
                        'buy_qty' => $info['buy_qty'],
                    );
                $this->model_ssl_shelf_order->addNewProduct($shelfOrderProductInfo);
                }
      }
        return $shelfOrderId;
    }

    protected function _addNewSystemTaskByShelfOrderId($data, $shelfIds, $products, $now) {
        $orderId = $this->_cpShelfOrderToOrder($data, $shelfIds, $products, $now);
        // $shelfOrderInfo = array('order_id' => $orderId, );
        // $this->model_ssl_shelf_order->modifyByPK($shelfOrderId, $shelfOrderInfo);
    }



     protected function _cpShelfOrderToOrder($data, $shelfIds, $products, $now) {
        $this->load->model('ssl/shelf_order');
        $this->load->model('ssl/order');
        $this->load->model('ssl/product');
        /* 订单主表 */
        // $shelfOrderInfo = $this->model_ssl_shelf_order->getByPK($shelfOrderId);
        $sql = "SELECT `customer_group_id`,`fullname`,`email`,`telephone`,`fax`,`user_id`,`logcenter_id` FROM `".DB_PREFIX."customer` WHERE `customer_id`='".$data['customerId']."'";
        $q = $this->db->query($sql);
        $customerGroupId = intval($q->row['customer_group_id']);
        $fullName = trim($q->row['fullname']);
        $email = trim($q->row['email']);
        $telephone = trim($q->row['telephone']);
        $fax = trim($q->row['fax']);
        $userId = intval($q->row['user_id']);
        $logcenterId = intval($q->row['logcenter_id']);

        $paymentMethod = $this->W_getPaymentMethod($data['paycode']);
        $countryId = $this->model_ssl_order->getCountryIdByName($data['sendaddress']['country']);
        $zoneId = $this->model_ssl_order->getZoneIdByName($countryId, $data['sendaddress']['zone']);
        $cityId = $this->model_ssl_order->getCityIdByName($zoneId, $data['sendaddress']['city']);

        $orderInfo = array(
            'store_id' => '0',
            'store_name' => '百货栈',
            'store_url' => 'http://m.bhz360.com/',
            'customer_id' => $data['customerId'],
            'customer_group_id' => $customerGroupId,
            'fullname' => $fullName,
            'email' => $email,
            'telephone' => $telephone,
            'fax' => $fax,
            'payment_fullname' => $data['sendaddress']['name'],
            'payment_company' =>  $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'payment_address' => $data['sendaddress']['address'],
            'payment_city' => $data['sendaddress']['city'],
            'payment_city_id' => $cityId,
            'payment_postcode' => '',
            'payment_country' => $data['sendaddress']['country'],
            'payment_country_id' => $countryId,
            'payment_zone' => $data['sendaddress']['zone'],
            'payment_zone_id' => $zoneId,
            'payment_address_format' => '',
            'payment_method' => $paymentMethod,
            'payment_code' => $data['paycode'],
            'shipping_fullname' => $data['sendaddress']['name'],
            'shipping_company' => $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'shipping_address' => $data['sendaddress']['address'],
            'shipping_city' => $data['sendaddress']['city'],
            'shipping_city_id' => $cityId,
            'shipping_postcode' => '',
            'shipping_country' => $data['sendaddress']['country'],
            'shipping_country_id' => $countryId,
            'shipping_zone' => $data['sendaddress']['zone'],
            'shipping_zone_id' => $zoneId,
            'shipping_address_format' => '',
            'shipping_method' => '免运费',
            'shipping_code' => 'free.free',
            'shipping_telephone' => $data['sendaddress']['tel'],
            'total' => $data['allprice'],
            'ori_total' => $data['allprice'],
            'order_status_id' => 20,
            'affiliate_id' => 0,
            'commission' => 0,
            'marketing_id' => 0,
            'tracking' => '',
            'language_id' => 1,
            'currency_id' => 4,
            'currency_code' => 'CNY',
            'currency_value' => 1,
            'date_added' => $now,
            'logcenter_id' => $logcenterId,
            'is_pay' => $ifPay,
            'recommend_usr_id' => $userId,
            'shelf_order_id' => implode(',', $shelfIds),
            'shelf_order_type' => 2,
        );
        $orderId = $this->model_ssl_order->addNew($orderInfo);

        if ($orderId) {
             foreach ($shelfIds as $key => $value) {
               $this->db->query("UPDATE shelf set neworder=".$orderId." where shelf_id=".$value);
             }
        //     $c = 1;
            foreach ($products as $key => $value) {
            foreach ($value as $unique=>$info) {
                $show_qty=$this->db->query("SELECT show_qty FROM shelf_product where shelf_product_id=".$info['shelf_product_id'])->row['show_qty'];
                $inventory=intval($show_qty)+intval($info['buy_qty']);
                $this->db->query("UPDATE shelf_product set show_qty=".$inventory." where shelf_product_id=".$info['shelf_product_id']);
              // list($productId, $productCode) = explode('_', $unique);
                //var_dump($products);die;
                $arr=explode('_', $unique);

                $productInfo = $this->model_ssl_product->getByPK($arr[0]);

                $orderProductInfo = array(
                    'order_id' => $orderId,
                    'product_id' => $productId,
                    'shelf_id' => $info['shelf_info']['S'],
                    'product_code' => $productCode,
                    'name' => $productInfo['name'],
                    'model' => $productInfo['model'],
                    'quantity' => $info['buy_qty'],
                    'price' => $info['price'],
                    'pay_price' => $info['price'],
                    'total' => $info['price']*$info['buy_qty'],
                    'pay_total' => $info['price']*$info['buy_qty'],
                    'tax' => 0,
                    'reward' => 0,
                    'vendor_id' => 0,
                    'order_status_id' => 0,
                    'commission' => 0,
                    'store_tax' => 0,
                    'vendor_tax' => 0,
                    'vendor_total' => 0,
                    'vendor_paid_status' => 0,
                    'title' => '',
                    'ship_status' => 0,
                    'shipped_time' => '0000-00-00 00:00:00',
                    'lack_quantity' => $info['buy_qty'],
                    'order_ids' => $c,
                );
                $orderProductId = $this->model_ssl_order->addNewProduct($orderProductInfo);
                $c++;
                /* 订单选项表 */
                $orderOptionInfo = array(
                    'order_id' => $orderId,
                    'order_product_id' => $orderProductId,
                    'product_option_id' => $productInfo['productOptionId'],
                    'product_option_value_id' => $productInfo['productOptionValueId'],
                    'name' => $productInfo['optionName'],
                    'value' => $productInfo['optionValueName'],
                    'type' => $productInfo['optionType'],
                );
                $this->model_ssl_order->addNewInTable($orderOptionInfo, 'order_option');
            }


        }
        /* 订单日志表 */
            $orderHistoryInfo = array(
                'order_id' => $orderId,
                'order_status_id' => 20,
                'date_added' => $now,
            );
            $this->model_ssl_order->addNewInTable($orderHistoryInfo, 'order_history');
            /* 订单总价表 */
            $orderTotalInfo = array(
                'order_id' => $orderId,
                'code' => 'sub_total',
                'title' => '小计',
                'value' =>  $data['allprice'],
                'sort_order' => '1',
            );
            $this->model_ssl_order->addNewInTable($orderTotalInfo, 'order_total');
            /* 订单总价表 */
            $orderTotalInfo = array(
                'order_id' => $orderId,
                'code' => 'total',
                'title' => '总计',
                'value' =>  $data['allprice'],
                'sort_order' => '100',
            );
          $this->model_ssl_order->addNewInTable($orderTotalInfo, 'order_total');
    }

        return $orderId;
    }

    protected function _getPaymentMethod($code) {
        $payMethodList = getPayMethod();
        //var_dump($payMethodList);die;
        foreach ($payMethodList as $v) {
            if ($v['code'] == $shelfOrderInfo['paycode']) {
                return $v['name'];
            }
        }
    }

     protected function W_getPaymentMethod($code) {
        $payMethodList = getPayMethod();
        //var_dump($payMethodList);die;
        foreach ($payMethodList as $v) {
            if ($v['code'] == $code) {
                return $v['name'];
            }
        }
    }

        //获取推荐商品
    public function getSearchProducts(){

        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);

        /*筛选条件*/
        if(isset($data['shelf_id'])){
            $filter['shelf_id'] = $data["shelf_id"];
        }

        if(isset($data['start'])){
            $filter['start'] = $data['start'];
        }
        else{
            $filter['start'] = 0;
        }

        if(isset($data['limit'])){
            $filter['limit'] = $data['limit'];
        }
        else{
            $filter['limit'] = 20;
        }

        if(isset($data['shelf_x'])){
            $shelf_x = $data['shelf_x'];
        }
        else{
            $shelf_x = 0;
        }

        if(isset($data['shelf_y'])){
            $shelf_y = $data['shelf_y'];
        }
        else{
            $shelf_y = 0;
        }

        if(isset($data['searchinput'])){
            $filter['searchinput'] = $data['searchinput'];
        }
        else{
            $filter['searchinput'] = "";
        }
        /*筛选条件*/

        $this->load->model('checkout/auto_purchase');
        $searchProducts = $this->model_checkout_auto_purchase->getSearchProducts($filter);

        $sp = array();
        foreach($searchProducts as $key => $v){
            $sp[$key] = $this->getProductInfo($v);
            if($sp[$key] != null){
                $sp[$key]['shelf_quantity'] = $v['minimum'];
                $sp[$key]['shelf_x'] = $shelf_x;
                $sp[$key]['shelf_y'] = $shelf_y;
                $sp[$key]['addnum'] = 0;
            }
        }

        $json['searchproducts'] = array_values(array_filter($sp)); //去空数组重编index

        $this->response->setOutput(json_encode($json));

    }

}

?>
